package ubi.quando.ServerComm;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.osmdroid.util.GeoPoint;

import ubi.quando.App.Contact;
import ubi.quando.App.ContactWallet;
import ubi.quando.App.EventBase;
import ubi.quando.App.EventMeeting;
import ubi.quando.App.EventPickUp;
import ubi.quando.App.PickUpParticipant;
import ubi.quando.UI.RegisterActivity;
import ubi.quando.UI.UbiApplication;
import ubi.quando.c2dm.C2DMessaging;

import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;

//////////////////////////////////////////////////////
//
//          NOTIFICATIONS
//       ------------------
//
//    - Update - Someone confirmed
//    - You were invited
//    - GPS updates
//    - Started (ended) event
//
//
//////////////////////////////////////////////////////

public class IServerComm {

	private static final int OK = 100;
	private static final int ERROR = 101;

	private static final String URL_PREFIX = "https://ubiquando-huji.appspot.com/";// "http://localhost:8888/";//
	private static final String URL_REGISTER = "register/";
	private static final String URL_API = "api/";
	private static final String URL_CONNECT = "connect/";

	private static final String CREATE_MEET_EVENT = "0";
	private static final String CREATE_PCKP_EVENT = "1";
	private static final String CONFIRM_EVENT = "2";
	private static final String UPDATE_LOC = "3";
	private static final String GET_EVENT = "4";
	private static final String START_EVENT = "5";
	private static final String REMOVE_FROM_EVENT = "6";
	private static final String REMOVE_EVENT = "7";
	private static final String FRIEND_REQUEST = "8";
	private static final String ADD_CONTACT = "9";
	private static final String ADD_NEW_PICKUP_TO_MEETING = "10";
	private static final String ADD_PICKUP_TO_MEETING = "11";
	private static final String OFFER_PICKUP = "12";
	private static final String APPROVE_PICKUP = "13";
	private static final String GET_CLIENT = "14";

	private static final String APP_MAIL = "ubiquando.huji@gmail.com";
	private static final String GOOGLE_LOGIN_URL = "https://www.google.com/accounts/ClientLogin";
//	private static final int LATITUDE = 0;
//	private static final int LONGITUDE = 1;

	public static final String MEETING_EVENT = "0";
	public static final String PICKUP_EVENT = "1";

	public static final int MEETING_EVENT_INT = 0;
	public static final int PICKUP_EVENT_INT = 1;

	private static final int CLIENT = 0;
	private static final int EVENT = 1;
	
	private UbiApplication mApp;
	private String mClientName;
	private String mRegistrationId;
	private MyJsonReader mReader;
	private ServerWriter mWriter;

	public void register(String email, String pwd, String name,
			UbiApplication application) {
		mApp = (UbiApplication) application;
		mReader = new MyJsonReader(this.mApp);
		mWriter = new ServerWriter(this.mApp);
		// mClientLogin = googleLogin(email, pwd);
		mClientName = name;

		C2DMessaging.register(mApp, APP_MAIL);
	}

	public void registerServer(String registrationId, String email, String pwd) {
		this.mRegistrationId = registrationId;

		List<NameValuePair> postDataBuilder = new ArrayList<NameValuePair>();

		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(URL_PREFIX + URL_REGISTER);
		// post.addHeader("Content-Type", "application/json");
		postDataBuilder.add(new BasicNameValuePair("name", mClientName));
		postDataBuilder.add(new BasicNameValuePair("location", "0,0"));
		postDataBuilder.add(new BasicNameValuePair("registrationId",
				this.mRegistrationId));
		// postDataBuilder.add(new BasicNameValuePair("clientLogin",
		// "BLA"));
		postDataBuilder.add(new BasicNameValuePair("email", email));
		postDataBuilder.add(new BasicNameValuePair("pwd", pwd));

		String clientId = null;

		try {
			post.setEntity(new UrlEncodedFormEntity(postDataBuilder));
			HttpResponse response = client.execute(post);
			BufferedReader rd = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent()));

			clientId = mReader.getId(rd, CLIENT);
			
//			JsonReader json = new JsonReader(rd);
//			json.beginObject();
//			while (json.hasNext()) {
//				String name = json.nextName();
//				if (name.equals("CODE")) {
//					if (json.nextInt() == ERROR) {
//						break;
//					}
//				} else if (name.equals("client_id")) {
//					clientId = json.nextString();
//				}
//			}
//			json.endObject();
		} catch (IOException e) {
			return;
		}
		((RegisterActivity) mApp.getCurrentActivity())
				.onRegistered(new ContactWallet(clientId, mClientName));
	}

	public ContactWallet connect(String email, String pwd,
			UbiApplication application) {
		mApp = application;
		mReader = new MyJsonReader(this.mApp);
		mWriter = new ServerWriter(this.mApp);
		List<NameValuePair> postDataBuilder = new ArrayList<NameValuePair>();

		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(URL_PREFIX + URL_CONNECT);
		// post.addHeader("Content-Type", "application/json");
		postDataBuilder.add(new BasicNameValuePair("email", email));
		postDataBuilder.add(new BasicNameValuePair("pwd", pwd));
		postDataBuilder.add(new BasicNameValuePair("connection", "true"));

		ContactWallet cw = null;

		try {
			post.setEntity(new UrlEncodedFormEntity(postDataBuilder));
			HttpResponse response = client.execute(post);
			BufferedReader rd = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent()));

			cw = mReader.getContactWallet(rd);
			
//			JsonReader json = new JsonReader(rd);
//			json.beginObject();
//			while (json.hasNext()) {
//				String name = json.nextName();
//				if (name.equals("CODE")) {
//					int code = json.nextInt();
//					if (code == ERROR) {
//						return null;
//					}
//				} else if (name.equals("CLIENT")) {
//					cw = getContactWallet(json);
//				}
//			}
//			json.endObject();
		} catch (IOException e) {
			return null;
		}

		return cw;
	}

//	private ContactWallet getContactWallet(JsonReader json) throws IOException {
//		json.beginObject();
//		String id = null, name = null;
//		ArrayList<Contact> contacts = new ArrayList<Contact>();
//		ArrayList<EventBase> events = new ArrayList<EventBase>();
//		while (json.hasNext()) {
//			String arg = json.nextName();
//			if (arg.equals("name")) {
//				name = json.nextString();
//			} else if (arg.equals("id")) {
//				id = json.nextString();
//			} else if (arg.equals("contacts")) {
//				getContacts(contacts, json);
//			} else if (arg.equals("events")) {
//				getEvents(events, json);
//			} else {
//				return null;
//			}
//		}
//		json.endObject();
//
//		return new ContactWallet(id, contacts, events, name);
//	}

//	private void getEvents(ArrayList<EventBase> events, JsonReader json)
//			throws IOException {
//		json.beginArray();
//		while (json.hasNext()) {
//			json.beginObject();
//			String type = json.nextName();
//			if (type.equals("MEETING_EVENT")) {
//				getMeetingEvent(events, json);
//			} else if (type.equals("PICKUP_EVENT")) {
//				getPickupEvent(events, json);
//			}
//			json.endObject();
//		}
//		json.endArray();
//	}

//	private void getMeetingEvent(ArrayList<EventBase> events, JsonReader json)
//			throws IOException {
//		String id = null, name = null, /* destName = null, */creatorId = null, arg = null;
//		boolean started = false;
//		long time = 0;
//		GeoPoint dest = null;
//		ArrayList<Contact> participants = new ArrayList<Contact>();
//		ArrayList<EventBase> pickups = new ArrayList<EventBase>();
//
//		json.beginObject();
//		while (json.hasNext()) {
//			arg = json.nextName();
//			if (arg.equals("id")) {
//				id = json.nextString();
//			} else if (arg.equals("name")) {
//				name = json.nextString();
//			}/*
//			 * else if(arg.equals("destName")){ destName = json.nextString(); }
//			 */else if (arg.equals("dest")) {
//				String[] latlng = json.nextString().split(",");
//				dest = new GeoPoint(Integer.parseInt(latlng[LATITUDE]),
//						Integer.parseInt(latlng[LONGITUDE]));
//			} else if (arg.equals("creator")) {
//				creatorId = json.nextString();
//			} else if (arg.equals("time")) {
//				time = json.nextLong();
//			} else if (arg.equals("started")) {
//				started = json.nextBoolean();
//			} else if (arg.equals("participants")) {
//				getContacts(participants, json);
//			} else if (arg.equals("pickups")) {
//				getEvents(pickups, json);
//			}
//		}
//		json.endObject();
//
//		EventMeeting event = new EventMeeting(dest, new Date(time), creatorId,
//				participants);
//		event.setId(id);
//		event.SetName(name);
//		event.setStarted(started);
//		for (EventBase pickup : pickups) {
//			event.addPickUp((EventPickUp) pickup);
//		}
//		events.add(event);
//	}

//	private void getPickupEvent(ArrayList<EventBase> events, JsonReader json)
//			throws IOException {
//		String id = null, name = null, /* destName = null, */pickerId = null, creatorId = null, arg = null;
//		boolean started = false;
//		long time = 0;
//		GeoPoint dest = null, location = null;
//		ArrayList<PickUpParticipant> participants = new ArrayList<PickUpParticipant>();
//
//		json.beginObject();
//		while (json.hasNext()) {
//			arg = json.nextName();
//			if (arg.equals("id")) {
//				id = json.nextString();
//			} else if (arg.equals("name")) {
//				name = json.nextString();
//			}/*
//			 * else if(arg.equals("destName")){ destName = json.nextString(); }
//			 */else if (arg.equals("dest")) {
//				String[] latlng = json.nextString().split(",");
//				dest = new GeoPoint(Integer.parseInt(latlng[LATITUDE]),
//						Integer.parseInt(latlng[LONGITUDE]));
//			} else if (arg.equals("location")) {
//				String locationStr = json.nextString();
//				if (locationStr.equals("none")) {
//					location = null;
//				} else {
//					String[] latlng = locationStr.split(",");
//					location = new GeoPoint(Integer.parseInt(latlng[LATITUDE]),
//							Integer.parseInt(latlng[LONGITUDE]));
//				}
//			} else if (arg.equals("pickerId")) {
//				pickerId = json.nextString();
//			} else if (arg.equals("creator")) {
//				creatorId = json.nextString();
//			} else if (arg.equals("time")) {
//				time = json.nextLong();
//			} else if (arg.equals("started")) {
//				started = json.nextBoolean();
//			} else if (arg.equals("participants")) {
//				getPickUpParticipants(participants, json);
//			}
//		}
//		json.endObject();
//
//		EventPickUp event = new EventPickUp(dest, new Date(time), creatorId,
//				pickerId, participants);
//		event.setId(id);
//		event.SetName(name);
//		event.SetPickUpLocation(location);
//		event.setStarted(started);
//		events.add(event);
//	}

//	private void getPickUpParticipants(
//			ArrayList<PickUpParticipant> participants, JsonReader json)
//			throws IOException {
//		String id = null, location = null, locName = null, arg = null;
//		long time = 0;
//		json.beginArray();
//		while (json.hasNext()) {
//			json.beginObject();
//			if (json.nextName().equals("PICKUP_CONTACT")) {
//				json.beginObject();
//				while (json.hasNext()) {
//					arg = json.nextName();
//					if (arg.equals("id")) {
//						id = json.nextString();
//					} else if (arg.equals("locName")) {
//						locName = json.nextString();
//					} else if (arg.equals("location")) {
//						location = json.nextString();
//					} else if (arg.equals("time")) {
//						time = Long.parseLong(json.nextString());
//					}
//				}
//				json.endObject();
//			}
//			json.endObject();
//			String[] latlng = location.split(",");
//			GeoPoint gLocation = new GeoPoint(
//					Integer.parseInt(latlng[LATITUDE]),
//					Integer.parseInt(latlng[LONGITUDE]));
//			Contact contact = mApp.getContactById(id);
//			PickUpParticipant participant = new PickUpParticipant(gLocation,
//					new Date(time), contact);
//			participant.setLocName(locName);
//			participants.add(participant);
//		}
//		json.endArray();
//	}

//	private void getContacts(ArrayList<Contact> contacts, JsonReader json)
//			throws IOException {
//		json.beginArray();
//		while (json.hasNext()) {
//			json.beginObject();
//			if (json.nextName().equals("CONTACT")) {
//				contacts.add(parseContact(json));
//			}
//			json.endObject();
//		}
//		json.endArray();
//	}

	public boolean disconnect() {
		List<NameValuePair> postDataBuilder = new ArrayList<NameValuePair>();

		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(URL_PREFIX + URL_CONNECT);
		// post.addHeader("Content-Type", "application/json");
		postDataBuilder.add(new BasicNameValuePair("clientId", mApp.getId()));
		postDataBuilder.add(new BasicNameValuePair("connection", "false"));

		try {
			post.setEntity(new UrlEncodedFormEntity(postDataBuilder));
			HttpResponse response = client.execute(post);
			BufferedReader rd = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent()));

			int result = mReader.getCode(rd);
			
			if(result == OK)
				return true;
//			JsonReader json = new JsonReader(rd);
//			json.beginObject();
//			while (json.hasNext()) {
//				String name = json.nextName();
//				if (name.equals("CODE")) {
//					int code = json.nextInt();
//					if (code == ERROR) {
//						return false;
//					} else if (code == OK) {
//						// hoooray
//					}
//				}
//			}
//			json.endObject();
		} catch (IOException e) {
			return false;
		}

		return false;
	}

//	private String writeInvites(Set<String> participants) throws IOException {
//		StringWriter sw = new StringWriter();
//		JsonWriter writer = new JsonWriter(sw);
//
//		writer.beginArray();
//		for (String contact : participants) {
//			writer.beginObject();
//			writer.name("participantId");
//			writer.value(contact);
//			writer.endObject();
//		}
//		writer.endArray();
//
//		return sw.toString();
//	}

//	private String writeMeetingInvites(Set<Contact> participants)
//			throws IOException {
//		Set<String> ids = new HashSet<String>();
//		for (Contact contact : participants) {
//			ids.add(contact.getId());
//		}
//		return writeInvites(ids);
//	}

//	private String writePickUpInvites(Collection<PickUpParticipant> participants)
//			throws IOException {
////		Set<String> ids = new HashSet<String>();
////		for (PickUpParticipant contact : participants) {
////			ids.add(contact.getContact().getId());
////		}
////		return writeInvites(ids);
//		StringWriter sw = new StringWriter();
//		JsonWriter writer = new JsonWriter(sw);
//
//		writer.beginArray();
//		for (PickUpParticipant contact : participants) {
//			writer.beginObject();
//			writer.name("participantId");
//			writer.value(contact.getContact().getId());
//			writer.name("location");
//			StringBuilder locationStr = new StringBuilder();
//			locationStr.append(contact.getLocation().getLatitudeE6()).append(',').append(contact.getLocation().getLongitudeE6());
//			writer.value(locationStr.toString());
//			writer.name("locName");
//			writer.value(contact.getLocName());
//			writer.name("time");
//			writer.value(contact.getDate().getTime());
//			writer.endObject();
//		}
//		writer.endArray();
//
//		return sw.toString();
//	}

	public String createMeetingEvent(Set<Contact> participants, String name,
			GeoPoint dest, Date date, String creatorId) {
		StringBuilder destStr = new StringBuilder();
		destStr.append(dest.getLatitudeE6()).append(",")
				.append(dest.getLongitudeE6());
		String id = null;

		List<NameValuePair> postDataBuilder = new ArrayList<NameValuePair>();

		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(URL_PREFIX + URL_API);
		// post.addHeader("Content-Type", "application/json");
		postDataBuilder
				.add(new BasicNameValuePair("method", CREATE_MEET_EVENT));
		postDataBuilder.add(new BasicNameValuePair("name", name));
		postDataBuilder.add(new BasicNameValuePair("creator", creatorId));
		postDataBuilder
				.add(new BasicNameValuePair("time", "" + date.getTime()));
		postDataBuilder.add(new BasicNameValuePair("dest", destStr.toString()));

		try {
			postDataBuilder.add(new BasicNameValuePair("invites",
					mWriter.writeMeetingInvites(participants)));
			post.setEntity(new UrlEncodedFormEntity(postDataBuilder));
			HttpResponse response = client.execute(post);
			BufferedReader rd = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent()));

			id = mReader.getId(rd, EVENT);
			
//			JsonReader json = new JsonReader(rd);
//			json.beginObject();
//			while (json.hasNext()) {
//				String arg = json.nextName();
//				if (arg.equals("CODE")) {
//					if (json.nextInt() == ERROR) {
//						return null;
//					}
//				} else if (arg.equals("event_id")) {
//					id = json.nextString();
//				}
//			}
//			json.endObject();
		} catch (IOException e) {
			return null;
		}
		return id;
	}

	public String createPickupEvent(Collection<PickUpParticipant> participants,
			String name, GeoPoint dest, Date date, GeoPoint location,
			String pickerId, String creatorId) {
		StringBuilder destStr = new StringBuilder();
		destStr.append(dest.getLatitudeE6()).append(",")
				.append(dest.getLongitudeE6());
		StringBuilder locationStr = new StringBuilder();
		if (location != null) {
			locationStr.append(location.getLatitudeE6()).append(",")
					.append(location.getLongitudeE6());
		} else {
			locationStr.append("none");
		}
		String id = null;

		List<NameValuePair> postDataBuilder = new ArrayList<NameValuePair>();

		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(URL_PREFIX + URL_API);
		// post.addHeader("Content-Type", "application/json");
		postDataBuilder
				.add(new BasicNameValuePair("method", CREATE_PCKP_EVENT));
		postDataBuilder.add(new BasicNameValuePair("name", name));
		postDataBuilder.add(new BasicNameValuePair("creator", creatorId));
		postDataBuilder
				.add(new BasicNameValuePair("time", "" + date.getTime()));
		postDataBuilder.add(new BasicNameValuePair("dest", destStr.toString()));
		postDataBuilder.add(new BasicNameValuePair("location", locationStr
				.toString()));
		postDataBuilder.add(new BasicNameValuePair("picker",
				(pickerId != null) ? pickerId : "none"));

		try {
			postDataBuilder.add(new BasicNameValuePair("invites",
					mWriter.writePickUpInvites(participants)));
			post.setEntity(new UrlEncodedFormEntity(postDataBuilder));
			HttpResponse response = client.execute(post);
			BufferedReader rd = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent()));

			id = mReader.getId(rd, EVENT);
			
//			JsonReader json = new JsonReader(rd);
//			json.beginObject();
//			while (json.hasNext()) {
//				String arg = json.nextName();
//				if (arg.equals("CODE")) {
//					if (json.nextInt() == ERROR) {
//						return null;
//					}
//				} else if (arg.equals("event_id")) {
//					id = json.nextString();
//				}
//			}
//			json.endObject();
		} catch (IOException e) {
			return null;
		}
		return id;
	}

	public boolean confirmation(String eventId, String contactId, int eventType, 
			String pickUpLocation, long pickUpTime, String locName) {

		List<NameValuePair> postDataBuilder = new ArrayList<NameValuePair>();

		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(URL_PREFIX + URL_API);
		// post.addHeader("Content-Type", "application/json");
		postDataBuilder.add(new BasicNameValuePair("method", CONFIRM_EVENT));
		postDataBuilder.add(new BasicNameValuePair("clientId", contactId));
		postDataBuilder.add(new BasicNameValuePair("eventId", eventId));
		postDataBuilder.add(new BasicNameValuePair("type", "" + eventType));
		
		if(eventType == PICKUP_EVENT_INT){
			postDataBuilder.add(new BasicNameValuePair("location", pickUpLocation));
			postDataBuilder.add(new BasicNameValuePair("locName", locName));
			postDataBuilder.add(new BasicNameValuePair("time", "" + pickUpTime));
		}

		try {
			post.setEntity(new UrlEncodedFormEntity(postDataBuilder));
			HttpResponse response = client.execute(post);
			BufferedReader rd = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent()));

			if(mReader.getCode(rd) == OK)
				return true;
			
//			JsonReader json = new JsonReader(rd);
//			json.beginObject();
//			while (json.hasNext()) {
//				String arg = json.nextName();
//				if (arg.equals("CODE")) {
//					int code = json.nextInt();
//					if (code == ERROR) {
//						return false;
//					} else if (code == OK) {
//						return true;
//					}
//				} else {
//					return false;
//				}
//			}
//			json.endObject();
		} catch (IOException e) {
			return false;
		}
		return false;
	}

	public boolean updateGeo(String id, /* String eventId, */GeoPoint location) {
		StringBuilder locationStr = new StringBuilder();
		locationStr.append(location).append(",")
				.append(location.getLongitudeE6());

		List<NameValuePair> postDataBuilder = new ArrayList<NameValuePair>();

		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(URL_PREFIX + URL_API);
		// post.addHeader("Content-Type", "application/json");
		postDataBuilder.add(new BasicNameValuePair("method", UPDATE_LOC));
		postDataBuilder.add(new BasicNameValuePair("clientId", id));
		postDataBuilder.add(new BasicNameValuePair("location", locationStr
				.toString()));
		try {
			post.setEntity(new UrlEncodedFormEntity(postDataBuilder));
			HttpResponse response = client.execute(post);
			BufferedReader rd = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent()));

			if(mReader.getCode(rd) == OK)
				return true;
			
//			JsonReader json = new JsonReader(rd);
//			json.beginObject();
//			while (json.hasNext()) {
//				String arg = json.nextName();
//				if (arg.equals("CODE")) {
//					int code = json.nextInt();
//					if (code == ERROR) {
//						return false;
//					} else if (code == OK) {
//						return true;
//					}
//				} else {
//					return false;
//				}
//			}
//			json.endObject();
		} catch (IOException e) {
			return false;
		}
		return false;
	}

	public boolean startEvent(String eventId, int eventType) {
		List<NameValuePair> postDataBuilder = new ArrayList<NameValuePair>();

		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(URL_PREFIX + URL_API);
		// post.addHeader("Content-Type", "application/json");
		postDataBuilder.add(new BasicNameValuePair("method", START_EVENT));
		postDataBuilder.add(new BasicNameValuePair("eventId", eventId));
		postDataBuilder.add(new BasicNameValuePair("type", "" + eventType));
		try {
			post.setEntity(new UrlEncodedFormEntity(postDataBuilder));
			HttpResponse response = client.execute(post);
			BufferedReader rd = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent()));

			if(mReader.getCode(rd) == OK)
				return true;
			
//			JsonReader json = new JsonReader(rd);
//			json.beginObject();
//			while (json.hasNext()) {
//				String arg = json.nextName();
//				if (arg.equals("CODE")) {
//					int code = json.nextInt();
//					if (code == ERROR) {
//						return false;
//					} else if (code == OK) {
//						return true;
//					}
//				} else {
//					return false;
//				}
//			}
//			json.endObject();
		} catch (IOException e) {
			return false;
		}
		return false;
	}

	public boolean addContact(String friendId) {
		List<NameValuePair> postDataBuilder = new ArrayList<NameValuePair>();

		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(URL_PREFIX + URL_API);
		// post.addHeader("Content-Type", "application/json");
		postDataBuilder.add(new BasicNameValuePair("method", ADD_CONTACT));
		postDataBuilder.add(new BasicNameValuePair("clientId1", mApp.getId()));
		postDataBuilder.add(new BasicNameValuePair("clientId2", friendId));
		try {
			post.setEntity(new UrlEncodedFormEntity(postDataBuilder));
			HttpResponse response = client.execute(post);
			BufferedReader rd = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent()));

			if(mReader.getCode(rd) == OK)
				return true;
			
//			JsonReader json = new JsonReader(rd);
//			json.beginObject();
//			while (json.hasNext()) {
//				String arg = json.nextName();
//				if (arg.equals("CODE")) {
//					int code = json.nextInt();
//					if (code == ERROR) {
//						return false;
//					} else if (code == OK) {
//						return true;
//					}
//				} else {
//					return false;
//				}
//			}
//			json.endObject();
		} catch (IOException e) {
			return false;
		}
		return false;
	}

	public boolean friendRequest(String email) {
		List<NameValuePair> postDataBuilder = new ArrayList<NameValuePair>();

		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(URL_PREFIX + URL_API);
		// post.addHeader("Content-Type", "application/json");
		postDataBuilder.add(new BasicNameValuePair("method", FRIEND_REQUEST));
		postDataBuilder.add(new BasicNameValuePair("clientId", mApp.getId()));
		postDataBuilder.add(new BasicNameValuePair("friend", email));
		try {
			post.setEntity(new UrlEncodedFormEntity(postDataBuilder));
			HttpResponse response = client.execute(post);
			BufferedReader rd = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent()));

			if(mReader.getCode(rd) == OK)
				return true;
			
//			JsonReader json = new JsonReader(rd);
//			json.beginObject();
//			while (json.hasNext()) {
//				String arg = json.nextName();
//				if (arg.equals("CODE")) {
//					int code = json.nextInt();
//					if (code == ERROR) {
//						return false;
//					} else if (code == OK) {
//						return true;
//					}
//				} else {
//					return false;
//				}
//			}
//			json.endObject();
		} catch (IOException e) {
			return false;
		}
		return false;
	}

	public boolean offerPickup(String eventId, String friendId) {
		List<NameValuePair> postDataBuilder = new ArrayList<NameValuePair>();

		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(URL_PREFIX + URL_API);
		// post.addHeader("Content-Type", "application/json");
		postDataBuilder.add(new BasicNameValuePair("method", OFFER_PICKUP));
		postDataBuilder.add(new BasicNameValuePair("clientId", mApp.getId()));
		postDataBuilder.add(new BasicNameValuePair("friendId", friendId));
		postDataBuilder.add(new BasicNameValuePair("eventId", eventId));
		try {
			post.setEntity(new UrlEncodedFormEntity(postDataBuilder));
			HttpResponse response = client.execute(post);
			BufferedReader rd = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent()));

			if(mReader.getCode(rd) == OK)
				return true;
			
//			JsonReader json = new JsonReader(rd);
//			json.beginObject();
//			while (json.hasNext()) {
//				String arg = json.nextName();
//				if (arg.equals("CODE")) {
//					int code = json.nextInt();
//					if (code == ERROR) {
//						return false;
//					} else if (code == OK) {
//						return true;
//					}
//				} else {
//					return false;
//				}
//			}
//			json.endObject();
		} catch (IOException e) {
			return false;
		}
		return false;
	}

	public boolean confirmPickup(String eventId) {
		List<NameValuePair> postDataBuilder = new ArrayList<NameValuePair>();

		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(URL_PREFIX + URL_API);
		// post.addHeader("Content-Type", "application/json");
		postDataBuilder.add(new BasicNameValuePair("method", APPROVE_PICKUP));
		postDataBuilder.add(new BasicNameValuePair("pickerId", mApp.getId()));
		postDataBuilder.add(new BasicNameValuePair("eventId", eventId));
		try {
			post.setEntity(new UrlEncodedFormEntity(postDataBuilder));
			HttpResponse response = client.execute(post);
			BufferedReader rd = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent()));

			if(mReader.getCode(rd) == OK)
				return true;
			
//			JsonReader json = new JsonReader(rd);
//			json.beginObject();
//			while (json.hasNext()) {
//				String arg = json.nextName();
//				if (arg.equals("CODE")) {
//					int code = json.nextInt();
//					if (code == ERROR) {
//						return false;
//					} else if (code == OK) {
//						return true;
//					}
//				} else {
//					return false;
//				}
//			}
//			json.endObject();
		} catch (IOException e) {
			return false;
		}
		return false;
	}

	public EventMeeting getMeetingEvent(String eventId) {
		EventMeeting event = null;
		List<NameValuePair> postDataBuilder = new ArrayList<NameValuePair>();

		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(URL_PREFIX + URL_API);
		// post.addHeader("Content-Type", "application/json");
		postDataBuilder.add(new BasicNameValuePair("method", GET_EVENT));
		postDataBuilder.add(new BasicNameValuePair("eventId", eventId));
		postDataBuilder.add(new BasicNameValuePair("type", MEETING_EVENT));
		try {
			post.setEntity(new UrlEncodedFormEntity(postDataBuilder));
			HttpResponse response = client.execute(post);
			BufferedReader rd = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent()));
			event = mReader.getMeetingEvent(rd);
		} catch (IOException e) {
			return null;
		}
		return event;
	}

	public EventBase getPickupEvent(String eventId) {
		EventPickUp event = null;
		List<NameValuePair> postDataBuilder = new ArrayList<NameValuePair>();

		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(URL_PREFIX + URL_API);
		// post.addHeader("Content-Type", "application/json");
		postDataBuilder.add(new BasicNameValuePair("method", GET_EVENT));
		postDataBuilder.add(new BasicNameValuePair("eventId", eventId));
		postDataBuilder.add(new BasicNameValuePair("type", PICKUP_EVENT));
		try {
			post.setEntity(new UrlEncodedFormEntity(postDataBuilder));
			HttpResponse response = client.execute(post);
			BufferedReader rd = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent()));
			event = mReader.getPickupEvent(new JsonReader(rd));
		} catch (IOException e) {
			return null;
		}
		return event;
	}

//	private EventMeeting parseMeetingEvent(BufferedReader rd)
//			throws IOException {
//		String id = null, name = null, creator = null;
//		long time = 0;
//		GeoPoint dest = null;
//		boolean started = false;
//		ArrayList<Contact> participants = new ArrayList<Contact>();
//		ArrayList<EventPickUp> pickups = new ArrayList<EventPickUp>();
//
//		JsonReader json = new JsonReader(rd);
//		json.beginObject();
//		if (json.nextName().equals("MEETING_EVENT")) {
//			json.beginObject();
//			while (json.hasNext()) {
//				String title = json.nextName();
//				if (title.equals("id")) {
//					id = json.nextString();
//				} else if (title.equals("name")) {
//					name = json.nextString();
//				} else if (title.equals("dest")) {
//					String[] latlng = json.nextString().split(",");
//					dest = new GeoPoint(Integer.parseInt(latlng[LATITUDE]),
//							Integer.parseInt(latlng[LONGITUDE]));
//				} else if (title.equals("creator")) {
//					creator = json.nextString();
//				} else if (title.equals("time")) {
//					time = json.nextLong();
//				} else if (title.equals("started")) {
//					started = json.nextBoolean();
//				} else if (title.equals("participants")) {
//					participants = parseParticipants(json);
//				} else if (title.equals("pickups")) {
//					pickups = parsePickups(json);
//				}
//			}
//		} else {
//			return null;
//		}
//		json.endObject();
//		EventMeeting event = new EventMeeting(dest, new Date(time), creator,
//				participants);
//		event.setPickUps(pickups);
//		event.setStarted(started);
//		event.setId(id);
//		event.SetName(name);
//		return event;
//	}

//	private ArrayList<EventPickUp> parsePickups(JsonReader json)
//			throws IOException {
//		ArrayList<EventPickUp> pickups = new ArrayList<EventPickUp>();
//		json.beginArray();
//		while (json.hasNext()) {
//			pickups.add(parsePickupEvent(json));
//		}
//		json.endArray();
//		return pickups;
//	}

//	private EventPickUp parsePickupEvent(JsonReader json) throws IOException {
//		String id = null, name = null, creator = null, picker = null;
//		long time = 0;
//		GeoPoint dest = null, location = null;
//		boolean started = false;
//		ArrayList<PickUpParticipant> participants = new ArrayList<PickUpParticipant>();
//
//		json.beginObject();
//		if (json.nextName().equals("PICKUP_EVENT")) {
//			json.beginObject();			
//			while (json.hasNext()) {
//				String title = json.nextName();
//				if (title.equals("id")) {
//					id = json.nextString();
//				} else if (title.equals("name")) {
//					name = json.nextString();
//				} else if (title.equals("dest")) {
//					String[] latlng = json.nextString().split(",");
//					dest = new GeoPoint(Integer.parseInt(latlng[LATITUDE]),
//							Integer.parseInt(latlng[LONGITUDE]));
//				} else if (title.equals("location")) {
//					String locationStr = json.nextString();
//					if (locationStr.equals("none")) {
//						location = null;
//					} else {
//						String[] latlng = locationStr.split(",");
//						location = new GeoPoint(Integer.parseInt(latlng[LATITUDE]),
//								Integer.parseInt(latlng[LONGITUDE]));
//					}
//				}else if (title.equals("creator")) {
//					creator = json.nextString();
//				} else if (title.equals("pickerId")) {
//					picker = json.nextString();
//				} else if (title.equals("time")) {
//					time = json.nextLong();
//				} else if (title.equals("started")) {
//					started = json.nextBoolean();
//				} else if (title.equals("participants")) {
//					participants = parsePickupParticipants(json);
//				}
//			}
//		} else {
//			return null;
//		}
//		json.endObject();
//		EventPickUp event = new EventPickUp(dest, new Date(time), creator,
//				picker, participants);
//		event.setStarted(started);
//		event.setId(id);
//		event.SetName(name);
//		event.SetPickUpLocation(location);
//		return event;
//	}

//	private ArrayList<PickUpParticipant> parsePickupParticipants(JsonReader json)
//			throws IOException {
//		ArrayList<PickUpParticipant> participants = new ArrayList<PickUpParticipant>();
//
//		json.beginArray();
//		while (json.hasNext()) {
//			json.beginObject();
//			if (json.nextName().equals("PICKUP_CONTACT"))
//				participants.add(parsePickUpContact(json));
//			json.endObject();
//		}
//		json.endArray();
//		return participants;
//	}

//	private PickUpParticipant parsePickUpContact(JsonReader json)
//			throws IOException {
//		String name = null, id = null, email = null, locName = null;
//		GeoPoint location = null;
//		long time = 0;
//		json.beginObject();
//		while (json.hasNext()) {
//			String title = json.nextName();
//			if (title.equals("id")) {
//				id = json.nextString();
//			} else if (title.equals("name")) {
//				name = json.nextString();
//			} else if (title.equals("location")) {
//				String[] latlng = json.nextString().split(",");
//				location = new GeoPoint(Integer.parseInt(latlng[LATITUDE]),
//						Integer.parseInt(latlng[LONGITUDE]));
//			} else if (title.equals("email")) {
//				email = json.nextString();
//			} else if (title.equals("locName")) {
//				locName = json.nextString();
//			} else if (title.equals("time")) {
//				time = json.nextLong();
//			}
//		}
//		json.endObject();
//		PickUpParticipant contact = new PickUpParticipant(location, new Date(
//				time), mApp.getContactById(id));
//		contact.setLocName(locName);
//		contact.setEmail(email);
//		contact.setName(name);
//		return contact;
//	}

//	private ArrayList<Contact> parseParticipants(JsonReader json)
//			throws IOException {
//		ArrayList<Contact> participants = new ArrayList<Contact>();
//
//		json.beginArray();
//		while (json.hasNext()) {
//			json.beginObject();
//			if (json.nextName().equals("CONTACT"))
//				participants.add(parseContact(json));
//			json.endObject();
//		}
//		json.endArray();
//		return participants;
//	}

//	private Contact parseContact(JsonReader json) throws IOException {
//		String name = null, id = null, email = null;
//		GeoPoint location = null;
//
//		json.beginObject();
//		while (json.hasNext()) {
//			String title = json.nextName();
//			if (title.equals("id")) {
//				id = json.nextString();
//			} else if (title.equals("name")) {
//				name = json.nextString();
//			} else if (title.equals("location")) {
//				String[] latlng = json.nextString().split(",");
//				location = new GeoPoint(Integer.parseInt(latlng[LATITUDE]),
//						Integer.parseInt(latlng[LONGITUDE]));
//			} else if (title.equals("email")) {
//				email = json.nextString();
//			}
//		}
//		json.endObject();
//		Contact contact = new Contact(name, id, location);
//		contact.setEmail(email);
//		return contact;
//	}

	public EventBase getEvent(String eventId, int eventType) {
		switch (eventType) {
		case MEETING_EVENT_INT:
			return getMeetingEvent(eventId);
		case PICKUP_EVENT_INT:
			return getPickupEvent(eventId);
		}
		return null;
	}

	public Contact getContact(String contactId) {
		Contact client = null;
		List<NameValuePair> postDataBuilder = new ArrayList<NameValuePair>();

		HttpClient httpClient = new DefaultHttpClient();
		HttpPost post = new HttpPost(URL_PREFIX + URL_API);
		// post.addHeader("Content-Type", "application/json");
		postDataBuilder.add(new BasicNameValuePair("method", GET_CLIENT));
		postDataBuilder.add(new BasicNameValuePair("clientId", contactId));
		try {
			post.setEntity(new UrlEncodedFormEntity(postDataBuilder));
			HttpResponse response = httpClient.execute(post);
			BufferedReader rd = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent()));

			JsonReader json = new JsonReader(rd);
			json.beginObject();
			if (json.nextName().equals("CONTACT")) {
				client = mReader.parseContact(json);
			}
			json.endObject();

		} catch (IOException e) {
			return null;
		}
		return client;
	}
}
